package com.kylin.module.baseapp.business;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.util.Config;
import com.kylin.common.util.UTool;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.community.business.MemberBlogic;
import com.kylin.module.community.orm.Member;
import com.kylin.module.shop.business.CompanyBlogic;
import com.kylin.module.shop.forms.CompanyForm;
import com.kylin.module.shop.orm.Company;
import com.kylin.module.shop.orm.CompanyCat;
import com.kylin.module.shop.orm.CompanyInd;
import com.kylin.module.user.orm.User;

public class BaseBlogic {
	protected static Logger log = Logger.getLogger(BaseBlogic.class);
     public void registerCompany(CompanyForm form)throws BusinessException{
 		User exampleUser = new User();
 		exampleUser.setUsername(form.getUsername());
 		List sameUsers = BaseHibernateDAO.findByExample(exampleUser);
 		if(sameUsers != null && sameUsers.size() > 0)
 			throw new BusinessException("已经有相同用户名("+form.getUsername()+")存在，请更改为其他用户名");
 		Company exampleCom = new Company();
 		exampleCom.setLanguage(form.getLanguage());
 		exampleCom.setName(form.getName());
 		List sameComs = BaseHibernateDAO.findByExample(exampleCom);
 		if(sameComs != null && sameComs.size() > 0)
 			throw new BusinessException("已经有同名的公司("+form.getName()+")存在，请更改公司名称");
log.debug(form);
 		User user = new User();
    	user.setUserrole(Constants.USER_ROLE_COMPANY);
    	user.setActive(Constants.ACTIVE_WAIT);
		user.setActive(new Short((short)0));
		user.setCountry(form.getCountry());
		user.setCreatedon(new Date());
		user.setLanguage(form.getLanguage());
		user.setUsername(form.getUsername());
		user.setEmail(form.getEmail());
		user = (User)BaseHibernateDAO.saveRtObj(user);
		if(form.getOtherLanguages() == null || form.getOtherLanguages().length ==0)
			throw new BusinessException("没有申请投放语言版本，请重新选择");
		for(int i=0;i<form.getOtherLanguages().length;i++){
			Company com = new Company();
			com.setUser(user);
			com.setActive(new Short( (short)0));
			com.setCreatedon(new Date());
			com.setLanguage(form.getOtherLanguages()[i]);

			if(form.getOtherLanguages()[i].equals(form.getLanguage())){
				com.setName(form.getName());
				com.setContact(form.getContact());
				com.setAddress(form.getAddress());
				com.setCompanyIntro(form.getCompanyIntro());
				com.setEmail(form.getEmail());
				com.setFax(form.getFax());
				com.setFaxArea(form.getFaxArea());
				com.setFaxCountry(form.getFaxCountry());
				com.setPhone(form.getPhone());
				com.setPhoneArea(form.getPhoneArea());
				com.setPhoneCountry(form.getPhoneCountry());
				com.setPostcode(form.getPostcode());
				if(form.getMainbusiness() != null)
				for(int k=0;k<form.getMainbusiness().length;k++){
					//商家的主营行业 
					Dict industry = (Dict) BaseHibernateDAO
									.findById(Dict.class, form.getMainbusiness()[k]);
					CompanyInd ci = new CompanyInd(industry,com,new Date());
					com.getMainbusiness().add(ci);
				}
				if(form.getMaincatproduct() != null)
				for(int k=0;k<form.getMaincatproduct().length;k++){
					//商家的 主营商品类别
					Dict catproduct = (Dict) BaseHibernateDAO
									.findById(Dict.class, form.getMaincatproduct()[k]);
					CompanyCat cp = new CompanyCat(catproduct, com,new Date() );
					com.getMaincatproduct().add(cp);
				}
			}
log.debug("\nSave com="+com.getName() +"("+com.getLanguage()+")");
			BaseHibernateDAO.save(com);
		}
     }
     
 	public User getLoginUser(String userName, String passWord,String language) throws BusinessException {
		User guest = new User();
		guest.setName("21name");
		guest.setUsername(userName);
		guest.setPassword(passWord);
		PropertyCondition[] pConditions = new PropertyCondition[] {
				new PropertyCondition("username", userName,PropertyCondition.OPERATOR_EQ ),
				new PropertyCondition("active", Constants.ACTIVE_ON,PropertyCondition.OPERATOR_EQ )
		};
		List list = BaseHibernateDAO.findByPropertyConditions(User.class, pConditions, null);
		if (list == null || list.size() ==0) {
			throw new BusinessException("无此注册用户");
		}
		User user = (User)list.get(0);
		if(passWord == null || ! passWord.equals(user.getPassword()) ){
			log.debug("cuentpass ="+user.getPassword() + ", inputpass="+passWord);
			throw new BusinessException("输入密码错误");
		}
		if(Constants.ACTIVE_OFF.equals(user.getActive())){
			log.debug("帐号处于被禁止状态: "+user.getUsername() + ", active="+user.getActive());
			throw new BusinessException("您的帐号处于被禁止状态，请联系管理员");
		}
		if(user.getUserrole().equals(Constants.USER_ROLE_COMPANY)){
			return new CompanyBlogic().getLoginUser(userName,language);
		}else{
			List members = BaseHibernateDAO.findByProperty(Member.class, "user", user);
			log.debug("find members.size ="+members.size());
			user.setSubs(members);
			return user;
		}
	}
 	
 	public User getAdminLoginUser(String userName, String passWord) throws BusinessException {
 		List adminList = Config.getList("adminList.user");
 		if(! adminList.contains(userName))
 		    throw new BusinessException("系统未设定此用户为系统管理员: "+userName);
 		PropertyCondition[] pConditions = new PropertyCondition[] {
				new PropertyCondition("username", userName,PropertyCondition.OPERATOR_EQ ),
				new PropertyCondition("active", Constants.ACTIVE_ON,PropertyCondition.OPERATOR_EQ )
		};
		List list = BaseHibernateDAO.findByPropertyConditions(User.class, pConditions, null);
		if (list == null || list.size() != 1) {
			throw new BusinessException("还未注册此用户");
		}
		User user = (User)list.get(0);
		if(passWord == null || ! passWord.equals(user.getPassword()) ){
			log.debug("cuentpass ="+user.getPassword() + ", inputpass="+passWord);
			throw new BusinessException("输入密码错误");
		}
		return user;
	}

 	public void sendLostPassword(String userName, String email) throws BusinessException{
		User user = new User();
		user.setUsername(userName);
 		List list = BaseHibernateDAO.findByExample(user);
 		if(list == null || list.size() == 0)
 			throw new BusinessException("错误的用户名");
 		user = (User) list.get(0);
 		if(email == null || !email.equals(user.getEmail()))
 			throw new BusinessException("您输入的email地址不正确");
 		UTool.sendGetPasswordMail(user.getUsername(),user.getPassword(),user.getEmail(),user.getLanguage());
 	}
 	
 	public static void main(String[]d){
 		List adminList = new ArrayList();
 		adminList.add("aaa");
 		adminList.add("bbb");
 		adminList.add("aaa");
 		boolean rs=adminList.contains("bb");
 		System.out.println("---------\nadminListsize="+adminList.size()+","+rs);
 	}
}
